/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.utils;

import com.entity.ConfigFile;
import com.entity.Host;
import com.entity.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 *
 * @author root
 */
public class XMLParser {

    private SAXBuilder builder;
    private File xmlFile;
    private Document document;
    private static XMLParser instance;
    private final String HOST_FILENAME = "host.xml";
    private final String SERVICES_FILENAME = "services.xml";
    private final String FILES_FILENAME = "files.xml";

    private XMLParser() {
        builder = new SAXBuilder();
    }

    public static XMLParser getInstance() {
        if (instance == null) {
            instance = new XMLParser();
        }
        return instance;
    }

    public Host parseHostXMLFiles(String path) {

        Host newHost = null;
        xmlFile = new File(path + HOST_FILENAME);

        try {
            //Se crea el documento a traves del archivo
            document = (Document) builder.build(xmlFile);
            //Se obtiene la raiz 'host'
            Element rootNode = document.getRootElement();
            //Se obtienen los atibutos de host
            String hostname = rootNode.getChildTextTrim("hostname");
            String ip = rootNode.getChildTextTrim("ip");
            String os = rootNode.getChildTextTrim("os");
            String version = rootNode.getChildTextTrim("version");
            String kernel = rootNode.getChildTextTrim("kernel");
            String arch = rootNode.getChildTextTrim("arch");
            String cpu = rootNode.getChildTextTrim("cpu");
            String cpuSpeed = rootNode.getChildTextTrim("cpu_speed");
            String cores = rootNode.getChildTextTrim("cores");
            String hthreading = rootNode.getChildTextTrim("hyperthreading");
            String memory = rootNode.getChildTextTrim("memory");
            String swap = rootNode.getChildTextTrim("swap");

            ArrayList<Service> serviceList = parseServiceXMLFile(path);
            ArrayList<ConfigFile> fileList = parseFilesXMLFile(path);

            newHost = new Host(hostname, cpu, cpuSpeed, hthreading, cores, "0", memory, swap, "0",
                    os, version, kernel, "test", arch, ip, serviceList, fileList);

        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }
        return newHost;
    }

    private ArrayList<Service> parseServiceXMLFile(String path) {

        ArrayList<Service> serviceList = null;
        xmlFile = new File(path + SERVICES_FILENAME);

        try {
            //Se crea el documento a traves del archivo
            document = (Document) builder.build(xmlFile);
            //Se obtiene la raiz 'tables'
            Element rootNode = document.getRootElement();

            //host que ejecuta el servicio
            String host = rootNode.getAttributeValue("host");

            //Se obtiene la lista de hijos de la raiz 'services'
            List list = rootNode.getChildren("service");

            //Se recorre la lista
            serviceList = new ArrayList<Service>();

            for (int i = 0; i < list.size(); i++) {
                //Se obtiene el elemento 'service'
                Element service = (Element) list.get(i);
                //Se obtiene la lista de hijos del tag 'service'
                String name = service.getChildTextTrim("name");
                String status = service.getChildTextTrim("status");
                String start = service.getChildTextTrim("start");
                String stop = service.getChildTextTrim("stop");
                String restart = service.getChildTextTrim("restart");
                String uptime = service.getChildTextTrim("uptime");

                serviceList.add(new Service(host, name, start, stop, restart, status, uptime));
            }
        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }
        return serviceList;
    }

    private ArrayList<ConfigFile> parseFilesXMLFile(String path) {

        ArrayList<ConfigFile> fileList = null;
        xmlFile = new File(path + FILES_FILENAME);

        try {
            //Se crea el documento a traves del archivo
            document = (Document) builder.build(xmlFile);
            //Se obtiene la raiz 'tables'
            Element rootNode = document.getRootElement();
            String host = rootNode.getAttributeValue("host");
            //Se obtiene la lista de hijos de la raiz 'files'
            List list = rootNode.getChildren("file");

            //Se recorre la lista
            fileList = new ArrayList<ConfigFile>();

            for (int i = 0; i < list.size(); i++) {
                //Se obtiene el elemento 'service'
                Element service = (Element) list.get(i);
                //Se obtiene la lista de hijos del tag 'service'
                String name = service.getChildTextTrim("name");
                String filePath = service.getChildTextTrim("path");
                fileList.add(new ConfigFile(host, filePath, name));
            }
        } catch (IOException io) {
            //System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            //System.out.println(jdomex.getMessage());
        }
        return fileList;
    }

    public String writeServiceItems(String path, String host, ArrayList<Service> items) {

        String result;
        xmlFile = new File(path + host + "/" + SERVICES_FILENAME);

        //Se crea el documento a traves del archivo
        document = new Document();
        //Se obtiene la raiz 'host'
        Element rootNode = new Element("services");
        rootNode.setAttribute("host", host);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Service serv = (Service) iter.next();
            Element newService = new Element("service");
            Element serviceName = new Element("name");
            serviceName.setText(serv.getDaemonName());
            Element serviceStatus = new Element("status");
            serviceStatus.setText(serv.getStatusCommand());
            Element serviceStart = new Element("start");
            serviceStart.setText(serv.getStartCommand());
            Element serviceRestart = new Element("restart");
            serviceRestart.setText(serv.getRestartCommand());
            Element serviceStop = new Element("stop");
            serviceStop.setText(serv.getStopCommand());
            Element serviceUptime = new Element("uptime");
            serviceUptime.setText("00:00:00");

            newService.addContent(serviceName);
            newService.addContent(serviceStatus);
            newService.addContent(serviceStart);
            newService.addContent(serviceRestart);
            newService.addContent(serviceStop);
            newService.addContent(serviceUptime);

            rootNode.addContent(newService);
        }
        document.setContent(rootNode);
        result = saveFile(document);
        return result;
    }

    public String writeFileItems(String path, String host, ArrayList<ConfigFile> items) {

        String result;
        xmlFile = new File(path + host + "/" + FILES_FILENAME);

        //Se crea el documento a traves del archivo
        document = new Document();
        //Se obtiene la raiz 'host'
        Element rootNode = new Element("files");
        rootNode.setAttribute("host", host);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            ConfigFile file = (ConfigFile) iter.next();
            Element newFile = new Element("file");
            Element fileName = new Element("name");
            fileName.setText(file.getName());
            Element filePath = new Element("path");
            filePath.setText(file.getPath());

            newFile.addContent(fileName);
            newFile.addContent(filePath);

            rootNode.addContent(newFile);
        }
        document.setContent(rootNode);
        result = saveFile(document);
        return result;
    }

    private String saveFile(Document document) {
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(document, new FileOutputStream(xmlFile));
        } catch (Exception e) {
            return "Se ha producido un error al guardar";
        }
        return "Operacion Exitosa";
    }
}